<template>
  <div id="wraper" v-show="showEdit">
    <el-dialog :title="article.id ? '修改文章' : '新增技巧'" :visible="true" @close="cancel" width="53%" :modal="false">
      <el-form :model="article" :rules="rules" ref="form">
        <el-form-item label="文章标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="article.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" :label-width="formLabelWidth" prop="articleBody">
          <!-- 富文本 -->
          <quill-editor ref="myQuillEditor" v-model="article.articleBody" :options="editorOption" />
        </el-form-item>
        <el-form-item label="视频地址" :label-width="formLabelWidth">
          <el-input v-model="article.videoURL" autocomplete="off" placeholder="请输入视频地址"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit">确认</el-button>
        </el-form-item>
      </el-form>
      <el-progress v-if="showPercent" style="width: 180px" :percentage="percent" />
    </el-dialog>
    <input type="file" ref="img" id="img" style="display: none" />
    <editimg @cancelEditImg="cancelEditImg" :editImgVisible.sync="editImgVisible" :imgSize="imgSize" :src="src" @finishEditImg="finishEditImg"></editimg>
  </div>
</template>
<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { update, add } from '@/api/hmmm/articles.js'
import COS from 'cos-js-sdk-v5'
import editimg from './editimg.vue'
var cos = new COS({
  SecretId: 'AKIDoQnukKdfQu73h4AzXoulLegRv84j7F6g', // 身份识别 ID
  SecretKey: 'LOAgvta0KN9drnTs0rRkmX1xc06vTmnX' // 身份密钥
})
export default {
  name: 'articledetail',
  components: {
    quillEditor,
    editimg
  },
  data () {
    return {
      title: '修改文章',
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      formLabelWidth: '80px',
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ list: 'ordered' }, { list: 'bullet' }],
              ['blockquote'],
              [{ align: ['', 'center', 'right', 'justify'] }],
              ['code-block', 'image', 'link']
            ],
            handlers: {
              image: (value) => {
                if (value) {
                  this.uploadImg()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      showPercent: false,
      percent: 0,
      editImgVisible: false,
      src: '',
      curImg: '',
      quill: null,
      editIndex: 0,
      imgSize: {
        curImgWidth: 0,
        curImgHeight: 0
      }
    }
  },
  methods: {
    // 在富文本编辑器中编辑图片
    editImg () {
      this.editImgVisible = true
    },
    getimgBase64 (img) {
      try {
        var canvas = document.createElement('canvas')
        this.imgSize.curImgWidth = img.width
        this.imgSize.curImgHeight = img.height
        canvas.width = img.width
        canvas.height = img.height
        var ctx = canvas.getContext('2d')
        img.setAttribute('crossorigin', 'anonymous')
        ctx.drawImage(img, 0, 0, img.width, img.height)
        console.dir(ctx)
        var dataURL = canvas.toDataURL('image/png')
        canvas = null // 释放
        console.dir(img)
        dataURL = dataURL.replace('data:image/jpeg;base64,', '')
        console.log(dataURL.length)
        this.src = dataURL
      } catch (error) {
        console.log('出错了')
        this.src = img.currentSrc
      }
    },
    getresult (val) {
      const _ = this
      const img = new Image()
      img.setAttribute('crossOrigin', 'Anonymous')
      img.src = val
      img.onload = function () {
        _.getimgBase64(img) // base64编码
      }
    },
    cancelEditImg () {
      var obj = document.getElementById('img')
      obj.value = null
      this.imgSize.curImgWidth = 0
      this.imgSize.curImgHeight = 0
    },
    finishEditImg (params) {
      this.cancelEditImg()
      this.showPercent = true
      const that = this
      cos.putObject(
        {
          Bucket: '742351109-1308685289',
          Region: 'ap-chongqing',
          Key: String(Date.now()),
          Body: params,
          StorageClass: 'STANDARD',
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        },
        (err, data) => {
          if (!err && data.statusCode === 200) {
            const src = 'http://' + data.Location
            if (that.curImg !== '') {
              console.log('修改')
              const midContent = that.quill.getContents()
              const mid = JSON.stringify({ image: src })
              that.quill.setContents(JSON.parse(JSON.stringify(midContent).replace(that.curImg, mid)))
            } else {
              that.quill.insertEmbed(that.editIndex, 'image', src)
              that.quill.setSelection(that.editIndex + 1)
            }
            that.$message({
              message: that.curImg !== '' ? '修改成功' : '添加成功',
              type: 'success'
            })
            setTimeout(() => {
              that.curImg = ''
              that.showPercent = false
              that.percent = 0
            }, 2000)
          }
        }
      )
    },
    uploadImg () {
      this.$refs.img.click()
    },
    cancel () {
      this.$refs.form.resetFields()
      this.$emit('update:showEdit', false)
      this.$emit('clear')
    },
    submit () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.article.id) {
            await update({
              articleBody: this.article.articleBody,
              id: this.article.id,
              title: this.article.title,
              videoURL: this.article.videoURL ? this.article.videoURL : null
            })
          } else {
            await add({
              articleBody: this.article.articleBody,
              id: null,
              title: this.article.title,
              videoURL: this.article.videoURL ? this.article.videoURL : null
            })
          }
          this.$message({
            message: !this.article.id ? '添加成功' : '修改成功',
            type: 'success'
          })
          this.cancel()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
  mounted () {
    setTimeout(() => {
      this.quill = this.$refs.myQuillEditor.quill
      const that = this
      document.getElementById('img').addEventListener('change', function () {
        if (this.files.length < 1) {
          that.$message.error('请选择图片')
          return false
        } else if (this.files[0].size > 5 * 1024 * 1024) {
          that.$message.error('不能超过5M')
          return false
        } else {
          // 记录下当前位置
          console.log('我运行了')
          that.editIndex = that.quill.getSelection().index
          that.getresult(window.URL.createObjectURL(this.files[0]))
          // that.getresult('https://t7.baidu.com/it/u=1785207335,3397162108&fm=193&f=GIF')
          that.editImg()
        }
      })
      // 监听双击事件，编辑图片
      document.getElementById('wraper').addEventListener('dblclick', function (e) {
        if (e.target.nodeName === 'IMG') {
          that.getimgBase64(e.target)
          // that.getresult(e.target.currentSrc)
          that.curImg = JSON.stringify({ image: e.target.currentSrc })
          that.editImg()
        }
      })
      // 监听鼠标over事件，编辑图片
      // document.getElementById('wraper').addEventListener('mouseover', function (e) {
      //   if (e.target.nodeName === 'IMG') {
      //     that.$message({
      //       message: '双击可编辑图片',
      //       duration: 1000
      //     })
      //   }
      // })
    }, 1000)
  },
  props: {
    showEdit: {
      type: Boolean,
      default: false
    },
    article: {
      required: true,
      type: Object
    }
  }
}
</script>
<style lang="scss" scoped>
.aritclebody {
  padding: 5px;
  border-top: 1px dashed #ccc;
  background-color: #f5f5f5;
}
::v-deep .ql-editor {
  height: 200px !important;
}
.tips {
  position: absolute;
  top: 0;
  right: 0;
  color: red;
  background-color: #ccc;
}
</style>
